package gitlab_sdk

import (
	"devops/pkg/git/git_model"
	"fmt"
	"strconv"

	"github.com/xanzy/go-gitlab"
)

// gitlab oyrasev73F46t7i848Lf
type gitlabClient struct {
	g *gitlab.Client
}

func NewGitlabClient(token string, url string) *gitlabClient {
	git, _ := gitlab.NewClient(token, gitlab.WithBaseURL(url))
	return &gitlabClient{g: git}
}

func (git *gitlabClient) GetRepos() ([]git_model.Repo, error) {
	projects, _, err := git.g.Projects.ListProjects(&gitlab.ListProjectsOptions{})
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	repos := make([]git_model.Repo, 0, len(projects))
	for _, p := range projects {
		repo := git_model.Repo{
			FullName: p.Name,
			Name:     p.Name,
			Owner: git_model.User{
				Login:     strconv.Itoa(p.ID),
				AvatarUrl: p.AvatarURL,
				HtmlUrl:   "",
			},
			Path:        p.Path,
			Description: p.Description,
			HtmlUrl:     p.HTTPURLToRepo,
			CloneUrl:    p.HTTPURLToRepo,
		}
		repos = append(repos, repo)
	}
	return repos, nil
}

func (git *gitlabClient) GetBranches(owner string, repo string) []git_model.Branch {
	gitlabBranches, _, err := git.g.Branches.ListBranches(owner, nil)
	if err != nil {
		return nil
	}
	branches := make([]git_model.Branch, 0, len(gitlabBranches))
	for _, b := range gitlabBranches {
		branches = append(branches, git_model.Branch{Name: b.Name, CommittedDate: git_model.CommittedDate(b.Commit.CommittedDate)})
	}
	return branches
}
